<template>
  <div class="release-info">
    <h2>心理资讯管理</h2>

    <!-- 文章列表 -->
    <div class="article-list">
      <el-card v-for="announcement in announcements" :key="announcement.announcementId" class="article-card">
        <div class="article-header">
          <div class="title-section">
            <h3>{{ announcement.title }}</h3>
            <el-tag :type="getTagType(announcement.classification)" size="small">
              {{ getClassificationLabel(announcement.classification) }}
            </el-tag>
          </div>
          <span class="article-time">{{ formatTime(announcement.createTime) }}</span>
        </div>
        <div class="article-content">
          <p class="content-preview" v-html="truncateContent(getTextContent(announcement.text))"></p>
          <div class="content-fade"></div>
        </div>
        <div class="article-footer">
          <span class="article-info">
            <el-icon><Document /></el-icon>
            <span>{{ getTextContent(announcement.text).length }}字</span>
          </span>
          <div class="article-actions">
            <el-button type="danger" link @click="handleDelete(announcement.announcementId)">删除</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 新增按钮 -->
    <div class="add-button">
      <el-button type="primary" @click="showDialog = true">
        <el-icon><Plus /></el-icon>新增文章
      </el-button>
    </div>

    <!-- 文章编辑对话框 -->
    <el-dialog
      v-model="showDialog"
      title="新增文章"
      width="60%"
    >
      <el-form :model="articleForm" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入文章标题" />
        </el-form-item>

        <el-form-item label="类型" prop="classification">
          <el-select v-model="articleForm.classification" placeholder="请选择文章类型">
            <el-option label="情感困扰" value="emotion" />
            <el-option label="学业压力" value="study" />
            <el-option label="职场压力" value="work" />
            <el-option label="家庭关系" value="family" />
            <el-option label="人际关系" value="social" />
            <el-option label="心理障碍" value="disorder" />
          </el-select>
        </el-form-item>

        <el-form-item label="内容" prop="text">
          <el-input
            v-model="articleForm.text"
            type="textarea"
            :rows="10"
            placeholder="请输入文章内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Document } from '@element-plus/icons-vue'
import {deleteAnnouncement, getDoctorAnnouncements } from '../../api/doctor'
import { createAnnouncement, type Announcement } from '../../api/announcement'

const announcements = ref<Announcement[]>([])
const showDialog = ref(false)
const formRef = ref()

// 文章表单
const articleForm = reactive({
  announcementId: 0,
  creatorId: Number(localStorage.getItem('doctorid')),
  title: '',
  classification: '',
  text: ''
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  classification: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  text: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 10, message: '内容不能少于10个字符', trigger: 'blur' }
  ]
}

// 获取文章列表
const fetchArticles = async () => {
  try {
    const res = await getDoctorAnnouncements(Number(localStorage.getItem('doctorid')))
    if (res.code === '200') {
      announcements.value = res.data
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    ElMessage.error('获取文章列表失败')
  }
}

// 获取分类标签类型
const getTagType = (classification: string) => {
  if (!classification) return ''
  const types: { [key: string]: string } = {
    'emotion': 'danger',
    'study': 'warning',
    'work': 'info',
    'family': 'success',
    'social': 'primary',
    'disorder': 'error'
  }
  return types[classification] || ''
}

// 获取分类显示文本
const getClassificationLabel = (classification: string) => {
  if (!classification) return '其他'
  const labels: { [key: string]: string } = {
    'emotion': '情感困扰',
    'study': '学业压力',
    'work': '职场压力',
    'family': '家庭关系',
    'social': '人际关系',
    'disorder': '心理障碍'
  }
  return labels[classification] || '其他'
}

// 截断内容显示
const truncateContent = (content: string) => {
  if (!content) return ''
  // 移除可能的HTML标签，只显示纯文本
  const plainText = content.replace(/<[^>]+>/g, '')
  return plainText.length > 100 ? plainText.substring(0, 100) + '...' : plainText
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return ''
  const date = new Date(time)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 删除文章
const handleDelete = async (announcementId: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这篇文章吗？', '提示', {
      type: 'warning'
    })
    
    const res = await deleteAnnouncement(announcementId)
    if (res.code === '200') {
      ElMessage.success('删除成功')
      fetchArticles()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除文章失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const res = await publishArticle(articleForm)
        
        if (res.code === '200') {
          ElMessage.success('发布成功')
          showDialog.value = false
          fetchArticles()
          // 重置表单
          articleForm.title = ''
          articleForm.classification = ''
          articleForm.text = ''
        } else {
          ElMessage.error(res.msg || '发布失败')
        }
      } catch (error) {
        console.error('提交文章失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 获取文本内容
const getTextContent = (text: string) => {
  if (!text) return ''
  try {
    const textObj = JSON.parse(text)
    return textObj.text || ''
  } catch {
    return text
  }
}

// 获取咨询师发布的资讯列表
const fetchDoctorAnnouncements = async () => {
  const doctorId = localStorage.getItem('doctorid')
  if (!doctorId) return
  
  loading.value = true
  try {
    const res = await getDoctorAnnouncements(Number(doctorId))
    if (res.code === '200') {
      announcements.value = res.data
    }
  } catch (error) {
    console.error('获取资讯列表失败:', error)
    ElMessage.error('获取资讯列表失败')
  } finally {
    loading.value = false
  }
}

// 发布资讯成功后刷新列表
const handleSuccess = () => {
  dialogVisible.value = false
  fetchDoctorAnnouncements()
}

onMounted(() => {
  fetchArticles()
  fetchDoctorAnnouncements()
})
</script>

<style scoped>
.release-info {
  padding: 20px;
}

.article-list {
  margin: 20px 0;
}

.article-card {
  margin-bottom: 20px;
}

.article-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.article-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.article-content {
  position: relative;
  margin: 16px 0;
}

.content-preview {
  color: #606266;
  line-height: 1.6;
  margin: 0;
  padding: 8px 0;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  max-height: 4.8em;
}

.content-fade {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 24px;
  background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1));
}

.article-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
  color: #909399;
  font-size: 14px;
}

.article-info {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
}

.article-time {
  font-size: 13px;
  color: #909399;
}

.add-button {
  margin-top: 20px;
  text-align: center;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}

.announcement-list {
  max-width: 900px;
  margin-top: 20px;
}

.announcement-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.announcement-content {
  padding: 16px;
}

.title {
  margin: 0 0 16px;
  font-size: 18px;
  color: #2c3e50;
}

.content-text {
  color: #606266;
  font-size: 15px;
  line-height: 1.6;
  margin-bottom: 16px;
  white-space: pre-wrap;
  word-break: break-word;
}

.meta {
  color: #909399;
  font-size: 14px;
}
</style>